<template>
	<a-modal width="auto" v-model:visible="formVisible" :align-center="true" @cancel="handleCancel" :footer="false"
		:mask-closable="false">
		<template #title>
			<a-image width="200" height="150" :src="$index.imgUrl+'registerLogo.png'" style="transform: translateY(7%);"
				draggable="false" :preview="false" />
		</template>
		<a-menu mode="horizontal" :default-selected-keys="['1']"
			style="width:auto;background-color:var(--color-bg);transform: translate(0%,-50%);" :accordion="true">
			<a-menu-item key="1">账号注册</a-menu-item>
		</a-menu>
		<a-form ref="myRegisterForm" size="medium" :model="registerForm" @submit-success="handleSuccess"
			style="width:calc(30vw);height:auto;padding-left: 5%;">
			<a-space direction="vertical" :size="15">
				<a-form-item class="itemStyle" field="userName" label="账号" :show-colon="true" :rules="[{required:true,message:'账号为必填项'},{minLength:5,message:'账号必须大于5位'},
				{match:/^(?!_)(?!.*?_$)[a-zA-Z0-9_]{4,9}$/,message:'账号必须是字母、数字、下划线且不能以下划线开始或结束'}]"
					:validate-trigger="['change','input']">
					<a-input v-model="registerForm.userName" placeholder="请输入账号..." style="width:calc(80%);"
						:max-length="10" show-word-limit>
						<template #prefix>
							<icon-user />
						</template>
					</a-input>
				</a-form-item>
				<a-form-item class="itemStyle" field="nickName" label="昵称" :show-colon="true" :rules="[{required:true,message:'昵称为必填项'},
				{match:/^(?!_)(?!.*?_$)[a-zA-Z0-9_\u4e00-\u9fa5]{4,10}$/,message:'昵称最小为4个字符且不能以下划线开始或结束'}]"
					:validate-trigger="['change','input']">
					<a-input v-model="registerForm.nickName" placeholder="请输入昵称..." style="width:calc(80%);"
						:max-length="10" show-word-limit>
						<template #prefix>
							<icon-stamp />
						</template>
					</a-input>
				</a-form-item>
				<a-form-item class="itemStyle" field="passWord" label="密&nbsp;&nbsp;&nbsp;码" :show-colon="true" :rules="[{required:true,message:'密码为必填项'},{minLength:5,message:'密码必须大于等于5位'},
					{match:/^(?!_)(?!.*_$)(?=.*[A-Za-z])(?=.*\d)[a-zA-Z0-9]{4,12}$/,message:'密码必须包含字母和数字且不能以下划线开始或结束'}]"
					:validate-trigger="['change','input']">
					<a-input-password v-model="registerForm.passWord" placeholder="请输入密码..." style="width:calc(80%);"
						:max-length="12" show-word-limit allow-clear>
						<template #prefix>
							<icon-safe />
						</template>
					</a-input-password>
				</a-form-item>
				<a-form-item class="itemStyle" field="rePassword" label="确认密码" :show-colon="true" :rules="[{required:true,message:'确认密码为必填项'},{minLength:5,message:'密码必须大于等于5位'},
					{match:/^(?!_)(?!.*_$)(?=.*[A-Za-z])(?=.*\d)[a-zA-Z0-9]{4,12}$/,message:'密码必须包含字母和数字且不能以下划线开始或结束'},{
					validator: (value, cb) => {
					  if (value !== registerForm.passWord) {
						cb('两次密码不一致')
					  }
					}
				  }]" :validate-trigger="['change','input']">
					<a-input-password v-model="registerForm.rePassword" placeholder="请输入确认密码..."
						style="width:calc(80%);" :max-length="12" show-word-limit allow-clear>
						<template #prefix>
							<icon-unlock />
						</template>
					</a-input-password>
				</a-form-item>
				<a-form-item class="itemStyle-telePhone" field="telePhone" label="电话" :show-colon="true" :rules="[{required:true,message:'电话为必填项'},{minLength:11,message:'电话必须为11位'},
				{match:/^1[3|5|7|8|9]\d{9}$/,message:'请输入正确的电话号码格式'}]" :validate-trigger="['change','input']">
					<a-row style="height: 32px;">
						<a-col :span="23" :offset="0">
							<a-input v-model="registerForm.telePhone" placeholder="请输入电话..." style="width:calc(60%);"
								:max-length="11" show-word-limit>
								<template #prefix>
									<icon-phone />
								</template>
							</a-input>
						</a-col>
						<a-col class="sendStyle" :span="20" :offset="14">
							<a-button id="send" style="width:90px;" @click="sendMessage">
								{{Number.isNaN(times)?发送短信:times}}
							</a-button>
						</a-col>
					</a-row>
				</a-form-item>
				<a-form-item class="itemStyle-verify" field="verify" label="验证码" :show-colon="true" :rules="[{required:true,message:'验证码为必填项'},{length:5,message:'验证码必须为5位'},
					{match:/^[0-9]{5}$/,message:'验证码必须由数字组成'}]" :validate-trigger="['change','input']">
					<a-row>
						<a-col :span="23" :offset="0">
							<a-input v-model="registerForm.verify" style="width:calc(85%);" placeholder="验证码"
								:max-length="5" show-word-limit>
								<template #prefix>
									<icon-tag />
								</template>
							</a-input>
						</a-col>
					</a-row>
				</a-form-item>
				<a-space direction="vertical" style="margin-left: 11%;margin-top: 10%;" :size="15">
					<a-row justify="center" align="center">
						<a-col :span="9" :offset="20">
							<a-link :hoverable="false">已有账号?去登录</a-link>
						</a-col>
					</a-row>
					<a-row :span="11">
						<a-button type="primary" class="buttonStyle" html-type="submit">注册</a-button>
					</a-row>
					<a-row :span="11">
						<a-button class="buttonStyle" @click="resetAll()">重置</a-button>
					</a-row>
				</a-space>
			</a-space>
		</a-form>
		<template #footer>
			<a-space direction="vertical" :size="15">
				<a-row :span="11">
					<a-button type="primary" class="buttonStyle" @click="loginAccount()">登录</a-button>
				</a-row>
				<a-row :span="11">
					<a-button class="buttonStyle" @click="resetAll()">重置</a-button>
				</a-row>
			</a-space>
		</template>
	</a-modal>
</template>

<script setup>
	import {
		ref,
		reactive,
		getCurrentInstance,
		onMounted
	} from 'vue';

	import apiUrl from '@/constant/index/apiUrl.js';
	import indexApi from '@/module/index/api/index.js';

	let {
		proxy
	} = getCurrentInstance();

	const props = defineProps({
		formVisible: Boolean,
		registerForm: Object
	});

	const emit = defineEmits();

	const apiUrlHome =
		import.meta.env.VITE_API_URL_HOME;

	let myRegisterForm = ref(null);

	let times = ref('发送短信');
	let registerStatus = reactive({});

	function handleOk() {
		emit('getregisterFormVisible', props.formVisible);
		document.getElementById('captCha').src = apiUrlHome + apiUrl.captCha;
	}

	function handleCancel() {
		emit('getregisterFormVisible', !props.formVisible);
		document.getElementById('captCha').src = apiUrlHome + apiUrl.captCha;
		myRegisterForm.value.resetFields();
	}

	async function handleSuccess(values) {
		console.log('formData', values);
		registerStatus.resp = await indexApi.toRegister(values);
		console.log('registerStatus.resp', registerStatus.resp);
		if(registerStatus.resp.flag == false && registerStatus.resp.message == '验证码校验失败'){
			proxy.$message.error('验证码校验失败');
		}
		else if(registerStatus.resp.flag == false && registerStatus.resp.message == '验证码过期'){
			proxy.$message.error('验证码过期');
		}
		else if(registerStatus.resp.flag == false && registerStatus.resp.message == '账号已被使用'){
			proxy.$message.error('账号已被使用');
		}
		else if(registerStatus.resp.flag == false && registerStatus.resp.message == '昵称已被使用'){
			proxy.$message.error('昵称已被使用');
		}
		else if(registerStatus.resp.flag == false && registerStatus.resp.message == '电话号码已被使用'){
			proxy.$message.error('电话号码已被使用');
		}
		else if(registerStatus.resp.flag == false && registerStatus.resp.message == '注册失败'){
			proxy.$message.error('注册失败');
		}
		else{
			proxy.$message.success('注册成功');
			emit('getregisterFormVisible', !props.formVisible);
			resetAll();
		}
		document.querySelector("body").setAttribute("style", "overflow: auto !important;");
	}

	function resetAll() {
		myRegisterForm.value.resetFields();
		myRegisterForm.value.clearValidate();
	}

	function sendMessage() {
		myRegisterForm.value.validateField(['userName', 'nickName', 'passWord', 'rePassword', 'telePhone'],async (rules) => {
			console.log('rules', rules);
			if (rules != undefined) {
				if (rules.hasOwnProperty('userName') || rules.hasOwnProperty('nickName') || rules.hasOwnProperty(
						'passWord') ||
					rules.hasOwnProperty('rePassword') || rules.hasOwnProperty('telePhone')) {
					console.log('表单验证未通过!')
					proxy.$message.warning('请先填写前五项信息!');
				}
			} else {
				console.log('表单验证通过!');
				let send = document.getElementById('send');
				if (send.textContent == '发送短信') {
					times.value = 10;
					let sendMessageTask = setInterval(() => {
						if (times.value >= 1) {
							times.value = times.value - 1;
						} else {
							clearInterval(sendMessageTask);
							times.value = '发送短信';
						}
					}, 1000);
				}
				console.log('tel',props.registerForm.telePhone);
				registerStatus.smsResp = await indexApi.getSmsCaptcha(props.registerForm.telePhone);
				registerStatus.flag = registerStatus.smsResp.flag;
				registerStatus.message = registerStatus.smsResp.message;
				console.log('flag',registerStatus.flag)
				if(registerStatus.flag == true){
					proxy.$message.success('短信发送成功');
				}
				else if(registerStatus.message == '短信发送失败'){
					proxy.$message.error('短信发送失败');
				}
				else if(registerStatus.message == '短信验证码未过期'){
					proxy.$message.warning('短信验证码未过期');
				}
			}
		});
	}

	async function refreshCaptCha() {
		let captCha = await indexApi.getCaptcha();
		//console.log('captCha',captCha);
		document.getElementById('captCha').src = apiUrlHome + apiUrl.captCha;
	}

	onMounted(() => {});
</script>

<style lang="less" scoped>
	@import '@/assets/index/css/registerForm.less';
</style>
